package com.hzqy.commons.utils.pay;

import org.apache.commons.lang.StringUtils;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 *
 */
public class GenerateSignUtil {

    /**
     *
     * @param toMd5
     * @return
     */
    public static String md5(String toMd5) {
        if (!StringUtils.isNotEmpty(toMd5)) {
            return null;
        }
        return toString(md5Private(toMd5.getBytes())).toUpperCase();
    }

    /**
     * 进行md5运算
     *
     * @param cs
     * @return
     */
    private static byte[] md5Private(byte[] cs) {
        byte[] rs = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            rs = md.digest(cs);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public static String toString(byte[] a) {
        if (a == null)
            return "null";
        if (a.length == 0)
            return "";

        StringBuilder buf = new StringBuilder();

        for (int i = 0; i < a.length; i++) {
            if (a[i] < 0)
                buf.append(Integer.toHexString(a[i] & 0xff));
            else if (a[i] < 16) {
                buf.append('0');
                buf.append(Integer.toHexString(a[i]));
            } else {
                buf.append(Integer.toHexString(a[i]));
            }
        }
        return buf.toString();
    }



    /**
     * 方法用途: 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序），并且生成url参数串<br>
     *
     * @param paraMap
     *            要排序的Map对象
     * @param urlEncode
     *            是否需要URLENCODE
     * @param keyToLower
     *            是否需要将Key转换为全小写 true:key转化成小写，false:不转化
     * @return
     */
    public static String formatUrlMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower) {
        String buff = "";
        Map<String, String> tmpMap = paraMap;
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造URL 键值对的格式
            StringBuilder buf = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (StringUtils.isNotBlank(item.getKey())) {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (urlEncode) {
                        val = URLEncoder.encode(val, "utf-8");
                    }
                    if (keyToLower) {
                        buf.append(key.toLowerCase() + "=" + val);
                    } else {
                        buf.append(key + "=" + val);
                    }
                    buf.append("&");
                }
            }
            buff = buf.toString();
            if (buff.isEmpty() == false) {
                buff = buff.substring(0, buff.length() - 1);
            }
        } catch (Exception e) {
            return null;
        }
        return buff;
    }

    public static void main(String[] args) {
        Map<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("partnerName", "1");
        hashMap.put("productId", "2");
        hashMap.put("systemid", "3");//渠道ID
        String stringPar = formatUrlMap(hashMap, false, true);
        //String signValue = SecureUtils.md5(stringPar + "&key=密钥"));
        //sign=signValue
    }
}
